<?php

class ScheduleLoop {

	private $scheduler;
	private $jobManager;
	private $processor;
	
	public function __construct($scheduler, $processor, $jobManager) {			
		$this->scheduler  = $scheduler;
		$this->processor = $processor;
		$this->jobManager = $jobManager;
	}
	
	public function run() {		
		$status = $this->scheduler->isRunning();		
		if($status !== false) {
			Yii::log('start scheduler error: ' . $status, 
				CLogger::LEVEL_ERROR, SCHEDULER_LOG);
			return 1;
		}
		Yii::log('scheduler started', CLogger::LEVEL_INFO, SCHEDULER_LOG);
		$loop_time = 0;
        $crashTimes = 0;
 		while (true) {		
			sleep(SCHE_CMD_LOOP_INTERVAL);
			$loop_time += SCHE_CMD_LOOP_INTERVAL;
				
            try {
                if($this->scheduler->isStandby()) {
                    Yii::log('scheduler is standby', CLogger::LEVEL_INFO, SCHEDULER_LOG);
                    continue;
                }
                $this->processor->processCommands();
                $baseDate = $this->scheduler->needSchedule();
                if($baseDate !== false && $loop_time >= SCHE_LOOP_INTERVAL) {
                    if(CREATE_ROUTINE_TASK === true) {
                        $jobs = $this->jobManager->getAllJobs($baseDate);
                        if($jobs === false)	{
                            Yii::log('job manager get jobs from database failed', CLogger::LEVEL_ERROR, SCHEDULER_LOG);							
                            return 1;
                        }

                        if(count($jobs) > 0) {
                            $this->scheduler->addJobs($jobs);
                            $this->scheduler->scheduleJobs($baseDate);
                        }

                        while(!$this->scheduler->saveScheduleDate($baseDate)) {
                            Yii::log('save scheduler log failed', CLogger::LEVEL_ERROR, SCHEDULER_LOG);
                            sleep(1);
                        }
                    }

                    $this->scheduler->scheduleTasks($baseDate);
                    $loop_time = 0;
                }
                $crashTimes = 0;//success 
            } 
            catch (Exception $e) {
                Yii::log('scheduler exception, message: '. $e->getMessage(), CLogger::LEVEL_ERROR, SCHEDULER_LOG);
                if ($crashTimes++ > 2) {
                    return 1;
                }
            }
			
 			if(time() >= strtotime(SCHE_EXIT_TIME)) {
				Yii::log('scheduler safe exit', CLogger::LEVEL_INFO, SCHEDULER_LOG);
				$this->scheduler->stop();
				return 0;
			}	
		}
	}
	
	
}

